package com.ldf.jrtsp.protocol;

import java.nio.ByteBuffer;

/**
 * 固定字符拆粘包
 *
 * @author lidaofu
 * @since 2024/4/9
 **/
public class DelimiterProtocol {
    private static String delimiterStr = "\r\n\r\n";

    public static byte[] decode(ByteBuffer byteBuffer) {
        byte[] delimiter = delimiterStr.getBytes();

        // 保存原始位置，以便在未找到完整包时恢复
        int initialPosition = byteBuffer.position();
        byteBuffer.mark();
        // 寻找分隔符出现的位置
        int delimiterIndex = -1;
        int delimiterLength = delimiter.length;
        int maxSearchLength = byteBuffer.remaining();
        for (int i = 0; i <= maxSearchLength - delimiterLength; i++) {
            boolean found = true;
            for (int j = 0; j < delimiterLength && found; j++) {
                if (byteBuffer.get(initialPosition + i + j) != delimiter[j]) {
                    found = false;
                }
            }
            if (found) {
                delimiterIndex = initialPosition + i;
                break;
            }
        }

        // 没有找到分隔符，说明缓冲区中没有完整包
        if (delimiterIndex == -1) {
            byteBuffer.reset();
            return null;
        }

        // 从当前位置到分隔符前的字节构成一个完整包
        int packetLength = delimiterIndex - byteBuffer.position();
        if (packetLength < 0) {
            throw new IllegalStateException("Invalid packet length: " + packetLength);
        }
        byte[] packet = new byte[packetLength];
        byteBuffer.get(packet);
        // 移动 position 过分隔符，准备读取下一个包
        byteBuffer.position(byteBuffer.position() + delimiterLength);
        return packet;
    }

}
